package dang.common;
//若出现不能初始dbutil的错误，在db.xml中增加密码，操作出错提示使用密码后再删除密码
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class DBUtil {
	private  BasicDataSource ds ;//= new BasicDataSource();//为线程安全的可以加static
	public  void setDs(BasicDataSource ds) {
		System.out.println("setDs"+ds);
		this.ds = ds;
	}
	private  ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
	

	
	//此方法得到的不是连接池的连接
	public  Connection openInThread() throws Exception{
		Connection con = threadLocal.get();
		if(null==con){
			con=ds.getConnection();
			threadLocal.set(con);
		}
		return con;
	}

	public  void closeInThread(){
		Connection con=threadLocal.get();
		if(null!=con){
			try {
				con.close();//断开有异常不管了
			} catch (SQLException e) {
				e.printStackTrace();
			}
			threadLocal.remove();
		}
	}
	
	public static void close(Connection con, Statement stm, ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
		} catch (Exception e) {
		}
		try {
			if (stm != null)
				stm.close();
		} catch (Exception e) {
		}
		try {
			if (con != null)
				con.close();
		} catch (Exception e) {
		}
	}
	
	public static void main(String[] args) throws Exception {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		Connection con=(Connection) ac.getBean("connection");
		Connection con1=(Connection) ac.getBean("connection");
		System.out.println(con==con1);
	}

	
}


